package org.pixelami.twisted.spread.pb
{
	import flash.events.Event;
	import flash.net.ObjectEncoding;
	import flash.utils.ByteArray;
	
	public class PeanutButter extends Protocol
	{
		public var knowDialects:Array = ["pb","None"];
		
		public var currentDialect:String;
		
		public function PeanutButter()
		{
			super();
		}
		
		override public function connectionMade():void
		{
			//trace("connected");
			currentDialect = null;
		}
		
		private function setDialect(dialect:String):void
		{
			currentDialect = dialect;
			//trace("currentDialect = "+currentDialect);
			
		}
		
		public function expressionReceived(obj:Object):void{}
		
		override public function dataReceived(obj:*):void
		{
			//trace("Broker dataReceived obj - "+obj);
			if(currentDialect)
			{
				expressionReceived(obj);
			}
			else
			{
				for each(var dialect:String in knowDialects)
				{
					for each(var d:String in obj)
					{
						if(d == dialect) 
						{
							setDialect(d);
							transport.writeUTFBytes(d);
							transport.flush();
							break;
						}
					}
				}
				
			}
		}
		
		public function sendEncoded(obj:Object):void
		{
			var ba:ByteArray = new ByteArray();
			ba.objectEncoding = ObjectEncoding.AMF0;
			
			writeList(obj,ba);
			
			prettyPrint(ba);
			
			transport.writeBytes(ba);
			transport.flush();
		}
		
	}
}